<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    :ok-button-props="{ props: { disabled: disableSubmit } }"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          <a-col :span="12">
            <a-form-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['name']" :disabled="disableSubmit" placeholder="请输入合同名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="合同编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['agreementCode']" :disabled="disableSubmit" placeholder="请输入合同编号"></a-input>
            </a-form-item>
          </a-col>
          <!--<a-col :span="12">-->
          <!--<a-form-item label="关键字" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
          <!--<a-select-->
          <!--mode="tags"-->
          <!--style="width: 100%"-->
          <!--:token-separators="[',']"-->
          <!--:disabled="disableSubmit"-->
          <!--v-decorator="['keywords', validatorRules.keywords]"-->
          <!--placeholder="请输入[盖章,签约日期]关键字,以英文逗号间隔"-->
          <!--&gt;-->
          <!--</a-select>-->
          <!--</a-form-item>-->
          <!--</a-col>-->
          <!--<a-col :span="12">
            <a-form-item label="合同类型" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
          <!--<j-dict-select-tag-->
          <!--type="list"-->
          <!--:disabled="disableSubmit"-->
          <!--@change="selectType"-->
          <!--v-decorator="['typeId', validatorRules.typeId]"-->
          <!--:trigger-change="true"-->
          <!--dictCode="DataDictionary,description,dictionaryCode,parentId = root&dictionaryTypeId = AgreementType"-->
          <!--placeholder="请选择输入合同类型"-->
          <!--/>-->
          <!--</a-form-item>-->
          <!--</a-col>-->
          <a-col :span="12">
            <a-form-item label="具体合同类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                v-decorator="['specificTypeId']"
                :disabled="disableSubmit"
                @change="selectTemplate"
                style="width: 100%"
                placeholder="请选择具体合同类型"
              >
                <a-select-option
                  v-for="specificId in specificList"
                  :key="specificId.dictionaryId"
                  :value="specificId.dictionaryCode"
                >
                  {{ specificId.description }}
                </a-select-option>
              </a-select>
              <!-- <j-dict-select-tag  type="list" v-decorator="['specificTypeId']" :trigger-change="true" dictCode="DataDictionary,description,dictionaryCode, dictionaryTypeId = AgreementType, " placeholder="请选择输入具体合同类型"/> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="合同模板名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                v-decorator="['templateId']"
                :disabled="disableSubmit"
                style="width: 100%"
                placeholder="请选择合同模板"
                @change="selectChange"
              >
                <a-select-option v-for="template in templateList" :key="template.id">
                  {{ template.name }}
                </a-select-option>
              </a-select>
              <!-- <j-dict-select-tag type="list" :disabled="disableSubmit" @change="selectChange" v-decorator="['templateId',validatorRules.templateId]" :trigger-change="true" dictCode="ClmTemplate,name,id, statusId = 2" placeholder="请选择合同模板"/> -->
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              label="甲方"
              :labelCol="{ xs: { span: 24 }, sm: { span: 4 } }"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 20 } }"
            >
              <j-search-select-tag
                v-if="fromCompanyTypeId == 'PERSON'"
                :disabled="disableSubmit"
                :async="false"
                @change="generatePurCode"
                dict="Person,name,partyId,typeId=EMPLOYEE"
                v-decorator="['fromCompanyId', validatorRules.fromCompanyId]"
                :trigger-change="true"
                placeholder="请选择甲方"
              />

              <j-search-select-tag
                v-else-if="fromCompanyTypeId == 'GROUP'"
                :disabled="disableSubmit"
                :async="false"
                @change="generatePurCode"
                :dict="'ClmCompany,companyName,id,statusId=2 & typeId='+ (typeId=='Purch'? 'Internal':'Cusomer') "
                v-decorator="['fromCompanyId', validatorRules.fromCompanyId]"
                :trigger-change="true"
                placeholder="请选择甲方"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              label="乙方"
              :labelCol="{ xs: { span: 24 }, sm: { span: 4 } }"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 20 } }"
            >
              <j-search-select-tag
                v-if="toCompanyTypeId == 'PERSON'"
                :disabled="disableSubmit"
                :async="false"
                @change="generateSaleCode"
                dict="Person,name,partyId,typeId=EMPLOYEE"
                v-decorator="['toCompanyId', validatorRules.toCompanyId]"
                :trigger-change="true"
                placeholder="请选择乙方"
              />
              <j-search-select-tag
                v-else-if="toCompanyTypeId == 'GROUP'"
                :disabled="disableSubmit"
                :async="false"
                @change="generateSaleCode"
                :dict="'ClmCompany,companyName,id,statusId=2 & typeId='+ (typeId=='Sale'? 'Internal':'Cusomer')"
                v-decorator="['toCompanyId', validatorRules.toCompanyId]"
                :trigger-change="true"
                placeholder="请选择乙方"
              />
            </a-form-item>
          </a-col>
           <a-col :span="12" v-if="typeId == 'Sale'">
            <a-form-item label="销售员" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                :disabled="disableSubmit"
                :async="false"
                dict="Person,name,partyId,typeId=EMPLOYEE"
                v-decorator="['salesperson', validatorRules.salesperson]"
                :trigger-change="true"
                placeholder="请选择销售员"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="签约时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                placeholder="请选择签约时间"
                :disabled="disableSubmit"
                v-decorator="['signDate', validatorRules.signDate]"
                :trigger-change="true"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="合同生效时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                placeholder="请选择合同生效时间"
                :disabled="disableSubmit"
                v-decorator="['fromDate']"
                :trigger-change="true"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="合同到期时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                placeholder="请选择合同到期时间"
                :disabled="disableSubmit"
                v-decorator="['thruDate']"
                :trigger-change="true"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="合同金额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number
                v-decorator="['agreementAmount']"
                :disabled="disableSubmit"
                placeholder="请输入合同金额(元)"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12" v-for="item in itemList" :key="item.id">
            <a-form-item :label="item.name" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-if="item.fieldTypeId == '1'"
                v-model="item.description"
                :placeholder="'请输入' + item.name"
              ></a-input>
              <j-date
                :disabled="disableSubmit"
                v-if="item.fieldTypeId == '2'"
                :placeholder="'请选择' + item.name"
                v-model="item.description"
                :trigger-change="true"
                style="width: 100%"
              />
              <!--
            <j-dict-select-tag type="list" :disabled="disableSubmit" v-model="item.description" v-if="item.fieldTypeId == '3'"
             :trigger-change="true" :dictCode="item.entityId+',description,dictionaryCode, dictionaryTypeId = '+item.dictionaryTypeId" :placeholder="'请选择'+item.name"/>
          -->
              <j-dict-select-tag
                type="list"
                :disabled="disableSubmit"
                v-model="item.description"
                v-if="item.fieldTypeId == '3'"
                :dictCode="item.entityId + ',description,description, dictionaryTypeId = ' + item.dictionaryTypeId"
                :placeholder="'请选择' + item.name"
              />
              <j-image-upload
                v-if="item.fieldTypeId == '5'"
                :disabled="disableSubmit"
                :isMultiple="false"
                v-model="item.description"
              ></j-image-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JDate from '@/components/jeecg/JDate'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JSearchSelectTag from '../../../../components/dict/JSearchSelectTag'
import JImageUpload from '@/components/jeecg/JImageUpload'

export default {
  name: 'ClmAgreementModal',
  components: {
    JDate,
    JDictSelectTag,
    JSearchSelectTag,
    JImageUpload
  },
  data() {
    return {
      disableSubmit: false,
      form: this.$form.createForm(this),
      title: '操作',
      width: 800,
      visible: false,
      model: {},
      itemList: [],
      newItemList: [],
      ClmAgreementItem: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        templateId: {
          rules: [{ required: true, message: '请选择合同模板名称!' }],
        },
        signDate: {
          rules: [{ required: true, message: '请选择签约时间!' }],
        },
        //        typeId: {
        //          rules: [{ required: true, message: '请选择合同类型!' }],
        //        },
        fromCompanyId: {
          rules: [{ required: true, message: '请选择甲方!' }],
        },
        toCompanyId: {
          rules: [{ required: true, message: '请选择乙方!' }],
        },
        salesperson: {
          rules: [{ required: true, message: '请选择销售员!' }],
        },
        keywords: {
          rules: [{ required: true, message: '请输入盖章关键字!' }],
        },
      },
      url: {
        add: '/online/special/api/createClmAgreement',
        edit: '/online/special/api/updateClmAgreement',
        get: '/online/api/getClmAgreement',
        getClmTemplateAndItem: '/online/api/getClmTemplateAndItem',
        selectDataDictionary: '/online/api/selectDataDictionary',
        selectClmTemplate: '/online/api/selectClmTemplate',
        getPurchaseAgreementCode: '/online/api/getPurchaseAgreementCode',
        getSaleAgreementCode: '/online/api/getSaleAgreementCode',
      },
      fromCompanyTypeId: 'GROUP',
      toCompanyTypeId: 'GROUP',
      specificList: [],
      templateList: [],
      typeId: this.$route.params.typeId,
      specificTypeId: '',
      toCompanyId: '',
      fromCompanyId: '',
    }
  },
  created() {},
  methods: {
    add() {
      this.edit({})
    },
    edit(record) {
      this.specificTypeId = ''
      this.toCompanyId = ''
      this.fromCompanyId = ''
      this.specificList = []
      this.templateList = []
      this.itemList = []
      let typeId = this.$route.params.typeId
      this.selectType(typeId)
      this.model.typeId = typeId
      this.form.resetFields()
      this.visible = true
      this.model = {}
      if (record.id) {
        httpAction(this.url.get, { id: record.id }, 'post').then((res) => {
          if (res.success) {

            this.toCompanyId = res.result.toCompanyId
            this.fromCompanyId = res.result.fromCompanyId
            if (res.result.specificTypeId) {
              this.selectTemplate(res.result.specificTypeId)
              if (res.result.typeId == "Purch") {
                this.generatePurCode(res.result.fromCompanyId)
              }
              else {
                this.generateSaleCode(res.result.toCompanyId)
              }
            }
            
            this.model = Object.assign({}, res.result)
            if (this.model.keywords) {
              this.model.keywords = this.model.keywords.replace('[', '')
              this.model.keywords = this.model.keywords.replace(']', '')
              this.model.keywords = this.model.keywords.split(',')
            }
            delete this.model['newItemList']
            this.newItemList = res.result.itemList
            if (this.newItemList) {
              let itemList = []
              this.newItemList.forEach((item) => {
                itemList.push({
                  fieldTypeId: item.fieldTypeId,
                  description: item.description,
                  name: item.name,
                  entityId: item.entityId,
                  dictionaryTypeId: item.dictionaryTypeId,
                })
              })
              this.itemList = itemList
            }
            if (this.model.fromCompanyTypeId) this.fromCompanyTypeId = this.model.fromCompanyTypeId
            if (this.model.toCompanyTypeId) this.toCompanyTypeId = this.model.toCompanyTypeId
            this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(
                  this.model,
                  'name',
                  'agreementCode',
                  'specificTypeId',
                  'templateId',
                  'fromCompanyId',
                  'toCompanyId',
                  'salesperson',
                  'signDate',
                  'agreementAmount',
                  'fromDate',
                  'thruDate',
                  'createDate',
                  'createBy',
                  'statusId',
                  'keywords'
                )
              )
            })
          }
        })
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
            this.model.statusId = '0'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          if (this.fromCompanyTypeId) this.model.fromCompanyTypeId = this.fromCompanyTypeId
          if (this.toCompanyTypeId) this.model.toCompanyTypeId = this.toCompanyTypeId
          let formData = Object.assign(this.model, values)
          if (this.itemList) {
            this.ClmAgreementItem = []
            this.itemList.forEach((item) => {
              this.ClmAgreementItem.push({
                name: item.name,
                description: item.description,
                fieldTypeId: item.fieldTypeId,
                entityId: item.entityId,
                dictionaryTypeId: item.dictionaryTypeId,
              })
            })
            formData.ClmAgreementItem = this.ClmAgreementItem
          }
          formData.typeId = this.$route.params.typeId
          httpAction(httpurl, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          'name',
          'agreementCode',
          'specificTypeId',
          'templateId',
          'fromCompanyId',
          'toCompanyId',
          'salesperson',
          'signDate',
          'agreementAmount',
          'fromDate',
          'thruDate',
          'createDate',
          'createBy',
          'statusId',
          'keywords'
        )
      )
    },
    selectChange(e) {
      if (e == undefined) {
        return false
      } else {
        getAction(this.url.getClmTemplateAndItem, { id: e }).then((res) => {
          if (res.success) {
            let itemList = res.result.clmTemplateItemList.reverse()
            itemList.forEach((item) => {
              if (item.itemDefaultValue) {
                item.description = item.itemDefaultValue
              }
            })
            this.itemList = itemList
          }
        })
      }
    },
    selectType(e) {
      this.typeId = e
      if (e == 'labor') {
        this.fromCompanyTypeId = 'GROUP'
        this.toCompanyTypeId = 'PERSON'
      } else {
        this.fromCompanyTypeId = 'GROUP'
        this.toCompanyTypeId = 'GROUP'
      }
      getAction(this.url.selectDataDictionary, { parentCode: e, dictionaryTypeId: 'AgreementType' }).then((res) => {
        if (res.success) {
          this.specificList = res.result.dictionaryList
        }
      })
    },
    selectTemplate(e) {
      this.specificTypeId = e
      let typeId = this.$route.params.typeId
      if(typeId == 'Sale' && this.model.agreementCode != ''){
        getAction(this.url.getSaleAgreementCode, {
            toCompanyId: this.toCompanyId,
            specificTypeId: e,
          }).then((res) => {
            if (res.success) {
              this.model.agreementCode = res.result.agreementCode
              this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(
                  this.model,
                  'agreementCode',
                )
              )
            })
            }
          })
      }
      if(typeId == 'Purch' && this.model.agreementCode != ''){
        getAction(this.url.getPurchaseAgreementCode, {
            fromCompanyId: this.fromCompanyId,
            specificTypeId: e,
          }).then((res) => {
            if (res.success) {
              this.model.agreementCode = res.result.agreementCode
              this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(
                  this.model,
                  'agreementCode',
                )
              )
            })
            }
          })
      }
      getAction(this.url.selectClmTemplate, { typeId: this.typeId, dictionaryCode: e }).then((res) => {
        if (res.success) {
           this.templateList = []   
           res.result.forEach((item) => {
              if (item.statusId == 2){
                  this.templateList.push(item)
               }
           })
          
          //this.templateList = res.result
        }
      })
    },
    generatePurCode(e) {
      this.fromCompanyId = e
      let typeId = this.$route.params.typeId
      if (typeId == 'Purch') {
        if (this.specificTypeId != '') {
          getAction(this.url.getPurchaseAgreementCode, {
            fromCompanyId: e,
            specificTypeId: this.specificTypeId,
          }).then((res) => {
            if (res.success) {
              this.model.agreementCode = res.result.agreementCode
              this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(
                  this.model,
                  'agreementCode',
                )
              )
            })
            }
          })
        } else {
          this.$message.error('请选择具体合同类型!')
        }
      } else {
        return false
      }
    },
    generateSaleCode(e) {
      this.toCompanyId = e
      let typeId = this.$route.params.typeId
      if (typeId == 'Sale') {
        if (this.specificTypeId != '') {
          getAction(this.url.getSaleAgreementCode, {
            toCompanyId: e,
            specificTypeId: this.specificTypeId,
          }).then((res) => {
            if (res.success) {
              this.model.agreementCode = res.result.agreementCode
              this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(
                  this.model,
                  'agreementCode',
                )
              )
            })
            }
          })
        } else {
          this.$message.error('请选择具体合同类型!')
        }
      } else {
        return false
      }
    },
  },
}
</script>
